# -*- coding: utf-8 -*-


# -----------------------------------------------------------------------------
# Make feature vector from Pair instance.
# Output must be hash-map.
# ----------------------------------------------------------------------------
def getFeature(pair):
    feat = dict()

    # bag of words
    bow_t = set((tok.attr['orig'] for tok in pair.text.itertokens()
                 if tok.isContent))
    bow_h = set((tok.attr['orig'] for tok in pair.hypo.itertokens()
                 if tok.isContent))

    for orig in bow_t:
        feat['t_bow(%s)'%orig] = 1.0
        
    for orig in bow_h:
        feat['h_bow(%s)'%orig] = 1.0

    for aw in bow_t & bow_h:
        feat['aw(%s)'%aw] = 1.0 # aligned token

    num_aw = len(bow_t & bow_h)
    feat['ratio_awh'] = num_aw / len(bow_h)
    feat['ratio_awt'] = num_aw / len(bow_t)

    # bag of chunks
    boc_t = set(chk for chk in pair.text.iterchunks())
    boc_h = set(chk for chk in pair.hypo.iterchunks())

    for ac in boc_t & boc_h:
        feat['ac(%s)'%ac] = 1.0 # aligned chunk

    num_ac = len(boc_t & boc_h)
    feat['ratio_ach'] = num_ac / len(boc_h)
    feat['ratio_act'] = num_ac / len(boc_t)

    get_content = lambda chk: [t.attr['orig'] for t in chk.toks
                               if t.isContent()]

    for i, src1 in enumerate(pair.text.chunks):
        ct_t_src = get_content(src1)

        if not ct_t_src:
            continue

        for j, src2 in enumerate(pair.hypo.chunks):
            ct_h_src = get_content(src2)

            if not ct_h_src:
                continue

            if ct_t_src == ct_h_src:
                joined = ','.join(ct_t_src)
                feat['ac_content(%s)'%joined] = 1.0 # align chunk content

            if ct_t_src[-1] == ct_h_src[-1]:
                feat['ac_head(%s)'%ct_t_src[-1]] = 1.0 # align chunk head

            if src1.head() >= 0 and src2.head() >= 0:
                dst1 = pair.text.getHeadChunk(i)
                dst2 = pair.hypo.getHeadChunk(j)
                ct_t_dst = get_content(dst1)
                ct_h_dst = get_content(dst2)

                if not ct_t_dst or not ct_h_dst:
                    continue

                if ct_t_src == ct_h_src and ct_t_dst == ct_h_dst:
                    joined_src = ','.join(ct_t_src)
                    joined_dst = ','.join(ct_t_dst)
                    
                    # align chunk dependency all
                    feat['acd_all(%s)(%s)' % (joined_src, joined_dst)] = 1.0

                if ct_t_src[-1] == ct_h_src[-1] and ct_t_dst[-1] == ct_h_dst[-1]:
                    hsrc = ct_t_src[-1]
                    hdst = ct_t_dst[-1]

                    # align chunk dependency head
                    feat['acd_head(%s)(%s)' % (hsrc,hdst)] = 1.0
    
    return feat
